package com.yuzhihao.writejvm.field;

import com.yuzhihao.writejvm.clazz.ClassInfo;
import com.yuzhihao.writejvm.format.ClassFormatEnum;
import com.yuzhihao.writejvm.read.Parse;
import lombok.Data;
import lombok.extern.log4j.Log4j2;

import java.io.DataInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * Each field is described by a field_info structure.
 *
 * <a href="https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.5">jvmdoc</a>
 * @author yzh
 * @since 2021年12月09日15:09:04
 */
@Data
@Log4j2
public class Fields implements Parse {

    private ClassFormatEnum cfe_fc = ClassFormatEnum.fields_count;

    protected int count;

    protected ClassInfo ci;

    private List<FieldInfo> infos = new ArrayList<>();

    @Override
    public void parse(DataInputStream dis, ClassInfo ci) {
        this.setCi(ci);
        try {
            this.count = Parse.byteToInt(cfe_fc.getB(), dis);

            int i = 0;
            while (i < this.count){
                FieldInfo info = new FieldInfo();
                info.parse(dis, ci);
                infos.add(info);
                i++;
            }

        } catch (IOException e) {
            log.error(e);
        }

        this.out(ci);
    }

    public void out(ClassInfo ci) {
        ci.setFields_count(this.count);
        ci.setField_info(this);
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        for (FieldInfo info : infos) {
            builder.append(info.print(this.ci));
        }
        return builder.toString();
    }
}
